import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';

class LyricLine {
  final Duration time;
  final String text;

  LyricLine(this.time, this.text);
}

class LyricWidget extends StatefulWidget {
  final List<LyricLine> lyrics;
  final Duration currentPosition;

  const LyricWidget({
    super.key,
    required this.lyrics,
    required this.currentPosition,
  });

  @override
  State<LyricWidget> createState() => _LyricWidgetState();
}

class _LyricWidgetState extends State<LyricWidget> {
  final ScrollController _scrollController = ScrollController();
  int _currentIndex = 0;
  bool _isUserScrolling = false;
  Timer? _resumeScrollTimer;

  static const double _lineHeight = 40.0;

  @override
  void didUpdateWidget(LyricWidget oldWidget) {
    super.didUpdateWidget(oldWidget);

    if (!_isUserScrolling) {
      _updateCurrentIndex();
      _scrollToCenter();
    }
  }

  void _updateCurrentIndex() {
    for (int i = 0; i < widget.lyrics.length; i++) {
      if (widget.currentPosition < widget.lyrics[i].time) {
        _currentIndex = (i - 1).clamp(0, widget.lyrics.length - 1);
        return;
      }
    }
    _currentIndex = widget.lyrics.length - 1;
  }

  void _scrollToCenter() {
    // final totalHeight = widget.lyrics.length * _lineHeight;
    final scrollViewHeight = _scrollController.position.viewportDimension;

    final targetOffset = (_currentIndex * _lineHeight) -
        (scrollViewHeight / 2 - _lineHeight / 2);
    if (targetOffset < 0 ||
        targetOffset > _scrollController.position.maxScrollExtent) return;

    _scrollController.animateTo(
      targetOffset,
      duration: const Duration(milliseconds: 300),
      curve: Curves.easeInOut,
    );
  }

  void _onUserScrollStart() {
    _isUserScrolling = true;
    _resumeScrollTimer?.cancel();
  }

  void _onUserScrollEnd() {
    _resumeScrollTimer?.cancel();
    _resumeScrollTimer = Timer(const Duration(seconds: 3), () {
      _isUserScrolling = false;
      _updateCurrentIndex();
      _scrollToCenter();
    });
  }

  @override
  void dispose() {
    _scrollController.dispose();
    _resumeScrollTimer?.cancel();
    super.dispose();
  }

  double _computeLineOpacity(int index) {
    final current = widget.currentPosition.inMilliseconds;
    final start = widget.lyrics[index].time.inMilliseconds;
    final end = index + 1 < widget.lyrics.length
        ? widget.lyrics[index + 1].time.inMilliseconds
        : start + 3000;

    final progress = ((current - start) / (end - start)).clamp(0.0, 1.0);
    return 0.6 + 0.4 * progress;
  }

  @override
  Widget build(BuildContext context) {
    return NotificationListener<UserScrollNotification>(
      onNotification: (notification) {
        if (notification.direction != ScrollDirection.idle) {
          _onUserScrollStart();
        } else {
          _onUserScrollEnd();
        }
        return false;
      },
      child: ListView.builder(
        controller: _scrollController,
        itemCount: widget.lyrics.length,
        itemBuilder: (context, index) {
          final lyric = widget.lyrics[index];
          final isCurrent = index == _currentIndex;

          return Container(
            height: _lineHeight,
            alignment: Alignment.center,
            child: AnimatedDefaultTextStyle(
              duration: const Duration(milliseconds: 300),
              style: TextStyle(
                fontSize: isCurrent ? 16 : 14,
                fontWeight: isCurrent ? FontWeight.bold : FontWeight.normal,
                color: isCurrent
                    // ? Colors.red.withOpacity(_computeLineOpacity(index))
                    ? const Color(0xFFf43f3b)
                    : Colors.grey,
              ),
              child: Text(
                lyric.text,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
            ),
          );
        },
      ),
    );
  }
}
